package com.juyu.miliao.common.security;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.juyu.miliao.common.msg.ErrorMsg;
import com.juyu.miliao.common.util.ServletTool;

/**
 * 返回json格式的未登录信息
 * @author zc
 *
 */
public class JsonAuthenticationEntryPoint implements AuthenticationEntryPoint{
	private final ObjectMapper objectMapper;
	private final ErrorMsg unauthenticatedMsg;

	public JsonAuthenticationEntryPoint(ObjectMapper objectMapper, ErrorMsg unauthenticatedMsg){
		this.objectMapper = objectMapper;
		this.unauthenticatedMsg = unauthenticatedMsg;
	}
	
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex)
			throws IOException, ServletException {
		response.setStatus(HttpStatus.UNAUTHORIZED.value());
//		StringBuffer url = request.getRequestURL();
		ServletTool.writeJSONStr(response, objectMapper.writeValueAsString(unauthenticatedMsg));
	}

}
